import binascii

from PyQt5.QtBluetooth import QLowEnergyDescriptor, QBluetoothUuid, QLowEnergyService
from PyQt5.QtWidgets import QWidget

from widget.descriptor_node_widget_ui import Ui_DescriptorNodeWidget
from widget.node_content_widget import NodeContentWidget


class DescriptorNodeWidget(QWidget, Ui_DescriptorNodeWidget):
    def __init__(self, service: QLowEnergyService, descriptor: QLowEnergyDescriptor, parent: NodeContentWidget, index, *args, **kwargs):
        super(DescriptorNodeWidget, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self._service = service
        self._descriptor = descriptor
        self._parent = parent
        self._index = index
        self._custom_init()
        self._signal_init()

    def _signal_init(self):
        self.write_pb.clicked.connect(self.on_write_button_clicked)
        self.read_pb.clicked.connect(self.on_read_button_clicked)

    def _custom_init(self):
        try:
            self.descriptor_name_value_lb.setText(self._descriptor.name())
            self.uuid_value_lb.setText(self._descriptor.uuid().toString())
            self._set_type()
            self.value_value_lb.setText(binascii.hexlify(self._descriptor.value()).decode('utf-8'))
        except Exception as e:
            print(e)

    def _set_type(self):
        type_str = ''
        if self._descriptor.type() == QBluetoothUuid.CharacteristicExtendedProperties:
            type_str = "Characteristic Extended Properties"
        elif self._descriptor.type() == QBluetoothUuid.CharacteristicUserDescription:
            type_str = "Characteristic User Description"
        elif self._descriptor.type() == QBluetoothUuid.ClientCharacteristicConfiguration:
            type_str = "Client Characteristic Configuration"
        elif self._descriptor.type() == QBluetoothUuid.ServerCharacteristicConfiguration:
            type_str = "Server Characteristic Configuration"
        elif self._descriptor.type() == QBluetoothUuid.CharacteristicPresentationFormat:
            type_str = "Characteristic Presentation Format"
        elif self._descriptor.type() == QBluetoothUuid.CharacteristicAggregateFormat:
            type_str = "Characteristic Aggregate Format"
        elif self._descriptor.type() == QBluetoothUuid.ValidRange:
            type_str = "Valid Range"
        self.type_value_lb.setText(type_str)

    def on_write_button_clicked(self):
        pass

    def on_read_button_clicked(self):
        pass







